package com.application.lucky.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.application.lucky.bean.jsonBean.FriendBean;
import com.application.lucky.bean.jsonBean.FriendListbean;
import com.application.lucky.config.Config;
import com.application.lucky.manager.ContactsManager;
import com.application.lucky.manager.UserManagers;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.RedPRequest;
import com.application.lucky.request.nav.UrlManager;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.qunar.im.base.common.ConversitionType;
import com.qunar.im.base.module.BaseIMMessage;
import com.qunar.im.base.module.IMMessage;
import com.qunar.im.base.util.LogUtil;
import com.qunar.im.core.services.QtalkNavicationService;
import com.qunar.im.ui.R;
import com.qunar.im.ui.adapter.ChatViewAdapter;
import com.qunar.im.ui.custommessage.TransferBean;
import com.qunar.im.ui.util.ProfileUtils;
import com.qunar.im.ui.view.baseView.ExtendBaseView;
import com.qunar.im.ui.view.baseView.processor.ProcessorFactory;
import com.qunar.im.ui.view.bigimageview.tool.utility.ui.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaokai on 15-9-15.
 */
public class ExtendChatViewAdapter extends ChatViewAdapter {
    private static final String TAG = "ExtendChatViewAdapter";
    private boolean shareStatus = false;
    private Map<String, IMMessage> sharingMsg = new HashMap<>();
    public String animateMsgId = null;

    public void changeShareStatus(boolean b) {
        shareStatus = b;
        if (!b) sharingMsg.clear();
    }

    public boolean isShareStatus() {
        return shareStatus;
    }

    public List<IMMessage> getSharingMsg() {
        List<IMMessage> list = new ArrayList<>();
        list.addAll(sharingMsg.values());
        return list;
    }


    public ExtendChatViewAdapter(Context context, String toId, Handler uiHandler, boolean showNick) {
        super(context, toId, uiHandler, showNick);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ExtendBaseView extendBaseView;
        LogUtil.d(TAG, "getView " + position);
        if (convertView == null) {
            extendBaseView = (ExtendBaseView) LayoutInflater.from(context.get()).inflate(R.layout.atom_ui_item_chat_extend, null);
            convertView = extendBaseView;
            extendBaseView.setGravatarHandler(gravatarHandler);
            extendBaseView.setLeftImageLongClickHandler(leftImageLongClickHandler);
            extendBaseView.setLeftImageClickHandler(leftImageClickHandler);

            extendBaseView.setContextMenuRegister(contextMenuRegister);
            extendBaseView.setRightSendFailureClickHandler(rightSendFailureClickHandler);
            extendBaseView.initFontSize();
        } else {
            extendBaseView = (ExtendBaseView) convertView;
        }
        SimpleDraweeView mLeftRoundedImageView = extendBaseView.mLeftRoundedImageView;
        SimpleDraweeView mRightRoundedImageView = extendBaseView.mRightRoundedImageView;

        ProfileUtils.displayGravatarRoundedCornerByImageSrc((((Activity) context.get())), UrlManager.getHeadPic(UserManagers.getInstance().getPic()), mRightRoundedImageView);

        FriendBean bean = ContactsManager.getInstance().searchFriendsByid(Config.IMIdUtils.getUserId(toId));
        String url = Config.HIDE_PIC;
        if (bean != null) {
            url = UrlManager.getHeadPic(bean.getHeadPic());

        }
        if (Config.IMIdUtils.isKefu(toId)) {
            mLeftRoundedImageView.setImageResource(R.drawable.icon_home_kefu_icon);
        } else {
            ProfileUtils.displayGravatarRoundedCornerByImageSrc((((Activity) context.get())), url, mLeftRoundedImageView);
        }

        final IMMessage message = getItem(position);
        if (message.getDirection() == IMMessage.DIRECTION_RECV &&
                TextUtils.isEmpty(message.getFromID())) {
            message.setFromID(toId);
        }
        try {
            extendBaseView.setMessage(this, handler, message, position);
        } catch (Exception e) {
            LogUtil.e(TAG, "ERROR", e);
        }
        extendBaseView.setLeftClickHandler(new LeftClickHandler() {
            @Override
            public void onLeftClickEvent(String jid) {
                if (message.getMsgType() == 24082) {
                    String ext = message.getExt();
                    TransferBean transferBean = new Gson().fromJson(ext, TransferBean.class);
                    new RedPRequest().red_receive(transferBean.transferId, new CallBackEx<BaseResponse<String>>() {
                        @Override
                        public void onSuccess(BaseResponse<String> stringBaseResponse) {

                            Toast.makeText(context.get(), "领取成功", Toast.LENGTH_SHORT).show();
                            UserManagers.getInstance().loadBalance();
                        }

                        @Override
                        public void onFailed(int code) {
                            if (code==60006) {
                                Toast.makeText(context.get(), "已经领取过了！", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(context.get(), "领取失败", Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
                }
            }
        });
        extendBaseView.setNickStatus(showNick
                && message.position == BaseIMMessage.LEFT);
//        extendBaseView.setReadStateShow(QtalkNavicationService.getInstance().isShowmsgstat() && !showNick);
        extendBaseView.setReadStateShow(QtalkNavicationService.getInstance().isShowmsgstat() && showReadState);
        if (shareStatus) {
            extendBaseView.setCheckboxEvent(null);
            if (ProcessorFactory.getMiddleType().contains(message.getMsgType()) ||
                    message.getType() == IMMessage.DIRECTION_MIDDLE ||
                    (message.getType() != ConversitionType.MSG_TYPE_GROUP && message.getType() != ConversitionType.MSG_TYPE_CHAT)) {
                extendBaseView.getCheckBox().setEnabled(false);
                extendBaseView.changeChbStatus(false);
                extendBaseView.getCheckBox().setVisibility(View.GONE);
            } else {
                extendBaseView.getCheckBox().setVisibility(View.VISIBLE);
                extendBaseView.getCheckBox().setEnabled(true);
                extendBaseView.changeChbStatus(sharingMsg.containsKey(message.getId()));
            }
            extendBaseView.setCheckboxEvent(checkedChangeListener);
            extendBaseView.saveId2Chb(message);
        }
        extendBaseView.changeShareStatus(shareStatus);
        if (animateMsgId != null && message.getId().equals(animateMsgId)) {
            animateMsgId = null;
            extendBaseView.startAnimate(3);
        }
        return convertView;
    }

    private CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                IMMessage message = (IMMessage) buttonView.getTag();
                if (isChecked) {
                    sharingMsg.put(message.getId(), message);
                } else {
                    sharingMsg.remove(message.getId());
                }
            } catch (Exception ex) {
                buttonView.setOnCheckedChangeListener(null);
                buttonView.setChecked(!isChecked);
                buttonView.setOnCheckedChangeListener(this);
            }
        }
    };
}
